package blog

import (
	"fmt"
	kinit "longblog/work/base/initialize"
	kroute "longblog/work/base/route"
	kcode "longblog/work/code"
	kbase "longblog/work/control/base"
	kdao "longblog/work/dao"
	kdaoblog "longblog/work/dao/blog"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type Article struct{}

func NewArticle() *Article {
	return &Article{}
}
func (h *Article) Load() (route []kroute.RouteWrapStruct) {
	route = make([]kroute.RouteWrapStruct, 0, 4)
	route = append(route, kbase.Wrap("GET", "/blog/article", h.indexHandle, kbase.MIDDLE_TYPE_CHECK_PERMISSION))
	route = append(route, kbase.Wrap("GETPOST", "/blog/article/add", h.addHandle, kbase.MIDDLE_TYPE_CHECK_PERMISSION))
	route = append(route, kbase.Wrap("GETPOST", "/blog/article/edit", h.editHandle, kbase.MIDDLE_TYPE_CHECK_PERMISSION))
	route = append(route, kbase.Wrap("POST", "/blog/article/del", h.delHandle, kbase.MIDDLE_TYPE_CHECK_PERMISSION))

	kbase.InsertMenu("/blog/article")
	kbase.InsertMenu("/blog/article/add")
	kbase.InsertMenu("/blog/article/edit")
	kbase.InsertMenu("/blog/article/del")
	return
}

type articleForm struct {
	Id            int64  `form:"id"`
	LangType      int64  `form:"lang_type" binding:"-"`
	SortNum       int64  `form:"sort_num"`
	Title         string `form:"title" binding:"-"`
	Content       string `form:"content" binding:"-"`
	Status        int64  `form:"status"`
	ArticleTypeId int64  `form:"article_type_id" binding:"-"`
}

// 首页handle
func (h *Article) indexHandle(c *gin.Context) {
	var param articleForm
	if err := c.ShouldBind(&param); err != nil {
		kinit.LogError.Println(err)
		kbase.SendErrorTokenJsonStr(c, kcode.PARAM_WRONG, "")
		return
	}

	page := kbase.GetParamInt64(c, "page")
	pageSize := kbase.GetParamInt64(c, "pageSize")
	if page <= 0 {
		page = 1
	}
	if pageSize <= 0 {
		pageSize = 5
	}
	offset := (page - 1) * pageSize

	sql := "select a.id,a.lang_type,a.title,a.sort_num,a.created_at,t.type_name " +
		"from article as a left join article_type as t on a.article_type_id=t.id where a.status=1 "
	sqlCount := "select count(*) as int64_data from article as a  where a.status=1 "
	if len(param.Title) > 0 {
		sql += fmt.Sprintf(" and a.title LIKE '%s%s%s' ", "%", param.Title, "%")
		sqlCount += fmt.Sprintf(" and a.title LIKE '%s%s%s' ", "%", param.Title, "%")
	}
	if param.LangType > 0 {
		sql += fmt.Sprintf(" and a.lang_type=%d ", param.LangType)
		sqlCount += fmt.Sprintf(" and a.lang_type=%d ", param.LangType)
	}
	if param.ArticleTypeId > 0 {
		sql += fmt.Sprintf(" and a.article_type_id=%d ", param.ArticleTypeId)
		sqlCount += fmt.Sprintf(" and a.article_type_id=%d ", param.ArticleTypeId)
	}
	sql += " order by a.sort_num desc limit ? offset ?"

	list := kdao.Scans(nil, sql, pageSize, offset)
	articleType, _ := kdaoblog.ObjArticleType.GetAll(nil)
	total := kdao.GetOneData(nil, sqlCount).Int64Data

	g := make(gin.H)
	g["token"] = c.GetString("token")
	g["title"] = param.Title
	g["langType"] = param.LangType
	g["articleTypeId"] = param.ArticleTypeId
	g["type"] = articleType
	g["list"] = list
	g["page"] = page
	g["pageSize"] = pageSize
	g["total"] = total
	c.HTML(http.StatusOK, "blog/article/index.html", g)
}

// 添加类别handle
func (h *Article) addHandle(c *gin.Context) {

	if c.Request.Method == "POST" {
		var param articleForm
		if err := c.ShouldBind(&param); err != nil {
			kinit.LogError.Println(err)
			kbase.ReturnJson(c, http.StatusOK, kcode.PARAM_WRONG, nil)
			return
		}
		if _, err := kdaoblog.ObjArticle.Insert(nil, param.LangType, param.Title, param.Content, param.ArticleTypeId); err != nil {
			kbase.ReturnJson(c, http.StatusOK, kcode.OPERATION_WRONG, nil)
			return
		}
		kbase.ReturnJson(c, http.StatusOK, kcode.SUCCESS_STATUS, nil)
		return
	}
	articleType, _ := kdaoblog.ObjArticleType.GetAll(nil)

	g := make(gin.H)
	g["token"] = c.GetString("token")
	g["type"] = articleType
	c.HTML(http.StatusOK, "blog/article/add.html", g)
}

// 编辑
func (h *Article) editHandle(c *gin.Context) {
	if c.Request.Method == "POST" {
		var param articleForm
		if err := c.ShouldBind(&param); err != nil {
			kinit.LogError.Println(err)
			kbase.ReturnJson(c, http.StatusOK, kcode.PARAM_WRONG, nil)
			return
		}
		m := make(map[string]interface{}, 4)
		m["sort_num"] = param.SortNum
		m["lang_type"] = param.LangType
		m["article_type_id"] = param.ArticleTypeId
		m["title"] = param.Title
		m["content"] = param.Content
		if err := kdaoblog.ObjArticle.UpdateMById(nil, param.Id, m); err != nil {
			kbase.ReturnJson(c, http.StatusOK, kcode.OPERATION_WRONG, nil)
			return
		}
		kbase.ReturnJson(c, http.StatusOK, kcode.SUCCESS_STATUS, nil)
		return

	}
	idStr, _ := c.GetQuery("id")
	id, _ := strconv.ParseInt(idStr, 10, 64)
	data, _ := kdaoblog.ObjArticle.GetById(nil, id)

	articleType, _ := kdaoblog.ObjArticleType.GetAll(nil)
	g := make(gin.H)
	g["type"] = articleType
	g["data"] = data
	g["token"] = c.GetString("token")
	c.HTML(http.StatusOK, "blog/article/edit.html", g)
}
func (h *Article) delHandle(c *gin.Context) {
	idStr := c.PostForm("id")
	id, _ := strconv.ParseInt(idStr, 10, 64)

	kdaoblog.ObjArticle.DeleteById(nil, id)
	kbase.ReturnJson(c, http.StatusOK, kcode.SUCCESS_STATUS, nil)
}
